#include <iostream>
#include <workflow/WFHttpServer.h>
#include <jsoncpp/json/json.h>
#include <unistd.h>
#include <memory>
#include "../include/bean/user.h"
#include "../include/service/loginservice.h"
using namespace std;

int xtyxtyxty = 10;

std::string getReqBody(WFHttpTask *task)
{
    std::string recv_str;
    const void *body;
    size_t recv_size = 1024;
    task->get_req()->get_parsed_body(&body, &recv_size);
    return std::string((char *)body, recv_size);
}

std::shared_ptr<User> getUser(WFHttpTask *task)
{
    Json::Value val_req, val_resp;
    if (strncmp(task->get_req()->get_method(), "POST", 4) != 0)
    {
        val_resp["status"] = Json::Value("error");
        task->get_resp()->append_output_body(val_resp.toStyledString());
        return std::shared_ptr<User>();
    }
    std::string recv_buffer = getReqBody(task);
    Json::Reader reader;
    if (!reader.parse(recv_buffer, val_req) || !val_req["user_name"].isString() || !val_req["user_pwd"].isString())
    {
        val_resp["status"] = Json::Value("error");
        task->get_resp()->append_output_body(val_resp.toStyledString());
        return std::shared_ptr<User>();
    }
    return std::make_shared<User>(val_req["user_name"].asString(), val_req["user_pwd"].asString());
}

void process(WFHttpTask *task)
{
    Json::Value val_req, val_resp;
    std::shared_ptr<User> user = getUser(task);
    if (user.get() == nullptr)
    {
        val_resp["status"] = Json::Value("wrong");
        task->get_resp()->append_output_body(val_resp.toStyledString());
        return;
    }
    cout << user->getUserName() << " " << user->getUserPwd() << endl;
    LoginService service;
    if (service.userCanLogin(user))
    {
        val_resp["status"] = Json::Value("ok");
        val_resp["token"] = Json::Value(service.getToken());
        task->get_resp()->append_output_body(val_resp.toStyledString());
    }
    else
    {
        val_resp["status"] = Json::Value("wrong");
        task->get_resp()->append_output_body(val_resp.toStyledString());
    }
}

int main()
{
    WFHttpServer server(process);
    if (server.start(10001) == 0)
    {
        getchar();
        server.stop();
    }
    return 0;
}